<template>
  <div class="w-full h-full pt-2">
    <!-- <a-select
      v-model:value="mrmCode"
      class="w-[335px]"
      :options="caseTypeOptions"
      :field-names="{ label: 'mrmName', value: 'mrmCode' }"
      placeholder="病历类型"
    /> -->
    <!-- 常规检查 -->
    <div v-if="(mrmCode === 'YKBL2' || mrmCode === 'YKBL3') && store.currentPatient.jzbh">
      <div class="flex justify-between">
        <BaseTitle :title="'常规检查'" />
        <img v-if="inspectShow" src="../../../../assets/images/down.png" class="w-6 h-6 mr-2 cursor-pointer" alt="" @click="tranInspect(false)" />
        <img v-else src="../../../../assets/images/up.png" class="w-6 h-6 mr-2 cursor-pointer" alt="" @click="tranInspect(true)" />
      </div>
      <InspectionTable v-if="inspectShow" :resource-data="inspectData" />
      <br />
    </div>
    <!-- 病历 -->
    <BaseTitle :title="'病历信息'">
      <div>
        <a-button @click="onClickHistory">调用病史</a-button>
        <a-button type="primary" ghost class="mx-2" @click="templateModalOpen = true">病历模板</a-button>
        <a-button class="mr-2" @click="onPrintMedical"> 打印病历单</a-button>
        <template v-if="mrmCode !== 'YKBL3'">
          <a-button :disabled="!formState.isCommit" @click="onPrint"> {{ printTitle }}</a-button>
          <a-button class="mx-2" @click="onPrintS"> 合并打印</a-button>
        </template>
      </div>
    </BaseTitle>
    <a-form class="mt-4" :disabled="!store.currentPatient.jzbh">
      <!-- 西医病历 -->
      <div v-if="mrmCode === 'XYBL'" class="case-table my-2">
        <div v-for="item in WMItems" :key="item.value" class="case-item">
          <template v-if="item.label === '处置'">
            <div class="label flex-col justify-center">
              <div>医嘱</div>
              <a-button class="-ml-2" size="small" type="link" @click="onGetDispose">获取医嘱</a-button>
            </div>
            <div class="content h-[54px]">
              <a-textarea v-model:value="formState[item.value]" :disabled="formState.isCommit" placeholder="请输入" :rows="4" />
            </div>
          </template>
          <template v-else>
            <div class="label" :class="{ required: item.label === '初步诊断' }">{{ item.label }}</div>
            <div class="content h-[54px]">
              <SelectTable
                v-if="item.label === '初步诊断'"
                v-model:value="formState[item.value]"
                type="诊断"
                :disabled="!store.currentPatient.jzbh || formState.isCommit"
                @select="onSelect(item.value, item.code, $event)"
              />
              <SelectTable
                v-if="item.label === '其他诊断'"
                v-model:value="formState[item.value]"
                multiple
                type="诊断"
                :auto-mark="false"
                :disabled="!store.currentPatient.jzbh || formState.isCommit"
                @select="onSelect(item.value, item.code, $event, true)"
              />
              <SelectTags
                v-else
                v-model:value="formState[item.value]"
                :disabled="formState.isCommit"
                show-setting
                show-new
                multiple
                type="医嘱字典"
                :search-params="{ blcybh: item.label }"
              />
            </div>
          </template>
        </div>
      </div>
      <!-- 中医 -->
      <div v-else-if="mrmCode === 'ZYBL'" class="case-table my-2">
        <div v-for="item in TCMItems" :key="item.value" class="case-item">
          <div class="label" :class="{ required: item.label === '临床诊断' }">{{ item.label }}</div>
          <div class="content h-[54px]">
            <SelectTable
              v-if="item.label === '临床诊断'"
              v-model:value="formState[item.value]"
              type="诊断"
              :disabled="!store.currentPatient.jzbh || formState.isCommit"
              @select="onSelect(item.value, item.code, $event)"
            />
            <SelectTable
              v-if="item.label === '中医诊断'"
              v-model:value="formState[item.value]"
              type="中医诊断"
              :disabled="!store.currentPatient.jzbh || formState.isCommit"
              @select="onSelect(item.value, item.code, $event)"
            />
            <SelectTable
              v-if="item.label === '中医证名'"
              v-model:value="formState[item.value]"
              type="中医证名"
              :disabled="!store.currentPatient.jzbh || formState.isCommit"
              @select="onSelect(item.value, item.code, $event)"
            />
            <SelectTags
              v-else
              v-model:value="formState[item.value]"
              :disabled="formState.isCommit"
              show-setting
              show-new
              multiple
              type="医嘱字典"
              :search-params="{ blcybh: item.label }"
            />
          </div>
        </div>
      </div>
      <!-- 眼科病历一 -->
      <div v-else-if="mrmCode === 'YKBL1'" class="case-table my-2">
        <div v-for="item in EYEItems1" :key="item.value" class="case-item">
          <div class="label h-10" :class="{ required: item.label === '初步诊断' }">{{ item.label }}</div>
          <div class="content">
            <div v-if="item.label === '初步诊断'" class="flex h-[54px]">
              <SelectTable
                v-model:value="formState[item.value]"
                type="诊断"
                :disabled="!store.currentPatient.jzbh || formState.isCommit"
                @select="onSelect(item.value, item.code, $event)"
              />
              <a-radio-group v-model:value="formState.bcYblb" :disabled="formState.isCommit" class="flex items-center" name="radioGroup">
                <a-radio value="OU">OU</a-radio>
                <a-radio value="OD">OD</a-radio>
                <a-radio value="OS">OS</a-radio>
              </a-radio-group>
            </div>
            <SelectTable
              v-else-if="item.label === '其他诊断'"
              v-model:value="formState[item.value]"
              multiple
              type="诊断"
              :auto-mark="false"
              :disabled="!store.currentPatient.jzbh || formState.isCommit"
              @select="onSelect(item.value, item.code, $event, true)"
            />
            <SelectTags
              v-else
              v-model:value="formState[item.value]"
              :disabled="formState.isCommit"
              show-setting
              show-new
              multiple
              :input-or-textarea="false"
              type="医嘱字典"
              :search-params="{ blcybh: item.label }"
            />
          </div>
        </div>
      </div>
      <!-- 眼科病历二 -->
      <div v-else-if="mrmCode === 'YKBL2'" class="case-table my-2">
        <div v-for="item in EYEItems2" :key="item.value" class="case-item">
          <div v-if="item.label !== '眼部检查'" class="label h-10" :class="{ required: item.label === '初步诊断' }">{{ item.label }}</div>
          <div v-else class="label-eye">
            <div class="eye-border-left">
              <div class="eye-border-left-con">眼部检查</div>
            </div>
            <div class="eye-border-right">
              <div v-for="(cItem, cIndex) in EYEChildItems" :key="cIndex" class="eye-border-right-con h-10">{{ cItem.label }}</div>
            </div>
          </div>
          <div class="content">
            <div v-if="item.label === '初步诊断'" class="flex h-[54px]">
              <SelectTable
                v-model:value="formState[item.value]"
                type="诊断"
                :disabled="!store.currentPatient.jzbh || formState.isCommit"
                @select="onSelect(item.value, item.code, $event)"
              />
              <a-radio-group v-model:value="formState.bcYblb" :disabled="formState.isCommit" class="flex items-center" name="radioGroup">
                <a-radio value="OU">OU</a-radio>
                <a-radio value="OD">OD</a-radio>
                <a-radio value="OS">OS</a-radio>
              </a-radio-group>
            </div>
            <div v-else-if="item.label === '眼部检查'">
              <div v-for="(cItem, cIndex) in EYEChildItems" :key="cIndex" class="eye-wrap h-10">
                <div v-if="cIndex == 0" class="flex h-full eye-box justify-center items-center">
                  <div class="eye-box-header-left h-full">右眼（OD）</div>
                  <div class="eye-box-header-right h-full">左眼（OS）</div>
                </div>
                <div v-else class="flex eye-item-box h-full">
                  <div class="eye-box-left h-full">
                    <div class="eye-box-left-br h-full w-1/2">
                      <a-input
                        v-if="cItem.key == '晶状体位置' || cItem.key == '眼底视盘'"
                        v-model:value="formData[cItem.valueOD]"
                        :disabled="formState.isCommit"
                        placeholder="请输入"
                      />
                      <SelectOptions
                        v-else
                        v-model:value="formData[cItem.valueOD]"
                        :select-mode="cItem.mode"
                        :type="cItem.key"
                        trigger="focus"
                        :auto-mark="false"
                        :disabled="!store.currentPatient.jzbh || formState.isCommit"
                        @select="onSelect(item.value, item.code, $event, true)"
                      />
                    </div>
                    <div class="h-full w-1/2">
                      <a-input v-if="cItem.memoOD" v-model:value="formData[cItem.memoOD]" :disabled="formState.isCommit" placeholder="备注" />
                      <div v-else class="no-data">—</div>
                    </div>
                  </div>
                  <div class="eye-box-right h-full">
                    <div class="eye-box-right-br h-full w-1/2">
                      <a-input
                        v-if="cItem.key == '晶状体位置' || cItem.key == '眼底视盘'"
                        v-model:value="formData[cItem.valueOS]"
                        :disabled="formState.isCommit"
                        placeholder="请输入"
                      />
                      <!-- multiple -->
                      <SelectOptions
                        v-else
                        v-model:value="formData[cItem.valueOS]"
                        :select-mode="cItem.mode"
                        :type="cItem.key"
                        trigger="focus"
                        :auto-mark="false"
                        :disabled="!store.currentPatient.jzbh || formState.isCommit"
                        @select="onSelect(item.value, item.code, $event, true)"
                      />
                    </div>
                    <div class="h-full w-1/2">
                      <a-input v-if="cItem.memoOS" v-model:value="formData[cItem.memoOS]" :disabled="formState.isCommit" placeholder="备注" />
                      <div v-else class="no-data">—</div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <SelectTable
              v-else-if="item.label === '其他诊断'"
              v-model:value="formState[item.value]"
              multiple
              type="诊断"
              :auto-mark="false"
              :disabled="!store.currentPatient.jzbh || formState.isCommit"
              @select="onSelect(item.value, item.code, $event, true)"
            />
            <SelectTags
              v-else
              v-model:value="formState[item.value]"
              :disabled="formState.isCommit"
              show-setting
              show-new
              multiple
              type="医嘱字典"
              :search-params="{ blcybh: item.label }"
            />
          </div>
        </div>
      </div>
      <!-- 眼科病历三 -->
      <div v-else-if="mrmCode === 'YKBL3'" class="case-table my-2">
        <div v-for="item in EYEItems3" :key="item.value" class="case-item">
          <div class="label h-10" :class="{ required: item.label === '初步诊断' }">{{ item.label }}</div>
          <div class="content">
            <div v-if="item.label === '初步诊断'" class="flex h-[54px]">
              <SelectTable
                v-model:value="formState[item.value]"
                type="诊断"
                :disabled="!store.currentPatient.jzbh || formState.isCommit"
                @select="onSelect(item.value, item.code, $event)"
              />
              <a-radio-group v-model:value="formState.bcYblb" :disabled="formState.isCommit" class="flex items-center" name="radioGroup">
                <a-radio value="OU">OU</a-radio>
                <a-radio value="OD">OD</a-radio>
                <a-radio value="OS">OS</a-radio>
              </a-radio-group>
            </div>
            <SelectTable
              v-else-if="item.label === '其他诊断'"
              v-model:value="formState[item.value]"
              multiple
              type="诊断"
              :auto-mark="false"
              :disabled="!store.currentPatient.jzbh || formState.isCommit"
              @select="onSelect(item.value, item.code, $event, true)"
            />
            <SelectTags
              v-else
              v-model:value="formState[item.value]"
              :disabled="formState.isCommit"
              show-setting
              show-new
              multiple
              :input-or-textarea="false"
              type="医嘱字典"
              :search-params="{ blcybh: item.label }"
            />
          </div>
        </div>
      </div>
      <div class="flex justify-end mt-4 mr-2">
        <a-button class="mr-4" @click="formState = {}">重置</a-button>
        <a-button class="mr-4" :disabled="formState.isCommit === 1" type="primary" @click="onSubmit()">保存</a-button>
        <a-button v-if="formState.isCommit !== 1" type="primary" :disabled="!saveStatus" @click="onSubmit('1', false)">提交</a-button>
        <a-button v-else type="primary" @click="onSubmit('0', false)">撤销</a-button>
      </div>
      <br />
      <TemplateModal v-model:open="templateModalOpen" :mrm-code="mrmCode" @success="onTempSuccess" />
    </a-form>
  </div>
</template>
<script setup>
import { onMounted, onUnmounted, ref, watch } from 'vue'
import { message } from 'ant-design-vue'
import { post } from '@/utils/request'
import SelectTags from '@/components/SelectTags'
import SelectTable from '@/components/SelectTable'
import useUserStore from '@/store/user'
import { getSystemConfig } from '@/utils/systemConfig'
import useStore from '../../store'
import InspectionTable from '../components/InspectionTable'
import TemplateModal from './TemplateModal'
import SelectOptions from './SelectOptions.vue'

const { empId } = useUserStore()
const props = defineProps({
  caseData: {
    type: Object,
    default: () => ({})
  },
  activeKey: {
    type: String,
    default: ''
  }
})
const setbh = getSystemConfig('ORGNIZATION_CODE') //组织机构代码
const host = getSystemConfig('HIS_MEDICAL_RECORD_URL') //跳转病历系统地址
const emit = defineEmits(['success'])
const store = useStore()
const inspectData = ref({})
const formState = ref({ bcYblb: 'OU' })
const formData = ref({})
const templateModalOpen = ref(false)
const isPrintStatus = ref()
const printTitle = ref('打印病程单')
const printType = ref()
const saveStatus = ref() // 判断是否有初步诊断，提交按钮是否可点击
const inspectShow = ref(true)
const WMItems = ref([
  { label: '主诉', value: 'bcZs' },
  { label: '病史', value: 'bcXbs' },
  { label: '既往史', value: 'bcJws' },
  { label: '体格检查', value: 'bcTgjc' },
  { label: '辅助检查', value: 'bcFzjc' },
  { label: '初步诊断', value: 'bcLczdZdmc', code: 'bcLczdZddm' },
  { label: '其他诊断', value: 'bcQtzdZdmc', code: 'bcQtzdZddm' },
  { label: '注意事项', value: 'bcZysx' },
  { label: '处置', value: 'bcCz' }
])
const TCMItems = ref([
  { label: '主诉', value: 'bcZs' },
  { label: '病史', value: 'bcXbs' },
  { label: '既往史', value: 'bcJws' },
  { label: '舌质', value: 'zybcSz' },
  { label: '舌苔', value: 'zybcSt' },
  { label: '脉象', value: 'zybcMx' },
  { label: '阳性体征', value: 'zybcYxtz' },
  { label: '辅助检查', value: 'bcFzjc' },
  { label: '辩证施治', value: 'zybcBzsz' },
  { label: '临床诊断', value: 'bcLczdZdmc', code: 'bcLczdZddm' },
  { label: '中医诊断', value: 'zybcZyzdZdmc', code: 'zybcZyzdZddm' },
  { label: '中医证名', value: 'zybcZyzxMc', code: 'zybcZyzxDm' }
])
const EYEItems1 = ref([
  { label: '主诉', value: 'bcZs' },
  { label: '现病史', value: 'bcXbs' },
  { label: '既往史', value: 'bcJws' },
  { label: '个人史', value: 'bcGrs' },
  { label: '家族史', value: 'bcJzs' },
  { label: '过敏史', value: 'bcGms' },
  { label: '眼部检查', value: 'bcYbjc' },
  { label: '辅助检查', value: 'bcFzjc' },
  { label: '初步诊断', value: 'bcLczdZdmc', code: 'bcLczdZddm' },
  { label: '其他诊断', value: 'bcQtzdZdmc', code: 'bcQtzdZddm' },
  { label: '处理意见', value: 'bcCl' }
  // { label: '交待', value: 'bcJd' }
])
const EYEItems3 = ref([
  { label: '主诉', value: 'bcZs' },
  { label: '现病史', value: 'bcXbs' },
  { label: '既往史', value: 'bcJws' },
  // { label: '个人史', value: 'bcGrs' },
  // { label: '家族史', value: 'bcJzs' },
  { label: '过敏史', value: 'bcGms' },
  { label: '眼部检查', value: 'bcYbjc' },
  { label: '辅助检查', value: 'bcFzjc' },
  { label: '初步诊断', value: 'bcLczdZdmc', code: 'bcLczdZddm' },
  { label: '其他诊断', value: 'bcQtzdZdmc', code: 'bcQtzdZddm' },
  { label: '处理意见', value: 'bcCl' }
  // { label: '交待', value: 'bcJd' }
])
const EYEItems2 = ref([
  { label: '主诉', value: 'bcZs' },
  { label: '现病史', value: 'bcXbs' },
  { label: '既往史', value: 'bcJws' },
  { label: '过敏史', value: 'bcGms' },
  { label: '眼部检查', value: 'bcYbjc' },
  { label: '初步诊断', value: 'bcLczdZdmc', code: 'bcLczdZddm' },
  { label: '其他诊断', value: 'bcQtzdZdmc', code: 'bcQtzdZddm' },
  { label: '处理意见', value: 'bcCl' }
  // { label: '交待', value: 'bcJd' }
])
const EYEChildItems = ref([
  { label: '眼别', value: 'bcZs' },
  { label: '眼睑（睑缘）', key: '睑缘', mode: 'combobox', valueOS: 'jy_os', valueOD: 'jy_od', memoOS: 'yl_bz_os', memoOD: 'yl_bz_od' },
  { label: '眼睑（睑板腺开口）', key: '睑板腺开口', mode: 'combobox', valueOS: 'jbxkk_os', valueOD: 'jbxkk_od', memoOS: '', memoOD: '' },
  { label: '泪器', key: '泪器', mode: 'combobox', valueOS: 'lq_os', valueOD: 'lq_od', memoOS: 'lq_bz_os', memoOD: 'lq_bz_od' },
  { label: '结膜', key: '结膜', mode: 'combobox', valueOS: 'jm_os', valueOD: 'jm_od', memoOS: 'jm_bz_os', memoOD: 'jm_bz_od' },
  { label: '角膜', key: '角膜', mode: 'combobox', valueOS: 'jmo_os', valueOD: 'jmo_od', memoOS: 'jmo_bz_os', memoOD: 'jmo_bz_od' },
  { label: '前房', key: '前房', mode: 'combobox', valueOS: 'qf_os', valueOD: 'qf_od', memoOS: 'qf_bz_os', memoOD: 'qf_bz_od' },
  { label: '虹膜', key: '虹膜', mode: 'combobox', valueOS: 'hm_os', valueOD: 'hm_od', memoOS: 'hm_qt_os', memoOD: 'hm_qt_od' },
  { label: '瞳孔', key: '瞳孔形态', mode: 'combobox', valueOS: 'tk_xt_os', valueOD: 'tk_xt_od', memoOS: 'tk_bz_os', memoOD: 'tk_bz_od' },
  { label: '晶状体', key: '晶状体', mode: 'combobox', valueOS: 'jzt_os', valueOD: 'jzt_od', memoOS: 'jzt_bz_os', memoOD: 'jzt_bz_od' },
  { label: '晶状体（位置）', key: '晶状体位置', mode: 'combobox', valueOS: 'jzt_os_wz', valueOD: 'jzt_od_wz', memoOS: '', memoOD: '' },
  { label: '眼底（玻璃体）', key: '玻璃体', mode: 'combobox', valueOS: 'blt_os', valueOD: 'blt_od', memoOS: 'blt_bz_os', memoOD: 'blt_bz_od' },
  { label: '眼底（视网膜）', key: '视网膜', mode: 'combobox', valueOS: 'yd_swm_os', valueOD: 'yd_swm_od', memoOS: 'yd_swmbz_os', memoOD: 'yd_swmbz_od' },
  {
    label: '眼底（黄斑中心凹反光）',
    key: '黄斑中心凹反光',
    mode: 'combobox',
    valueOS: 'yd_hbzxafg_os',
    valueOD: 'yd_hbzxafg_od',
    memoOS: 'yd_hbzxafgbz_os',
    memoOD: 'yd_hbzxafgbz_od'
  },
  { label: '眼底（视盘/CD）', key: '眼底视盘', mode: 'combobox', valueOS: 'yd_cd_os', valueOD: 'yd_cd_od', memoOS: '', memoOD: '' },
  { label: '其他（专科检查）', key: '其他检查', mode: 'tags', valueOS: 'qtzkjc_os', valueOD: 'qtzkjc_od', memoOS: '', memoOD: '' }
])
//获取处置
const onGetDispose = async () => {
  const res = await post('/outp/mzys/lnkAutoZlclLinkClicked', {
    jzbh: store.currentPatient.jzbh
  })
  const dataText = res.data.includes(formState.value.bcCz) ? res.data : formState.value.bcCz
  formState.value.bcCz = dataText || res.data
}

//获取病历类型
// const caseTypeOptions = ref([])
const mrmCode = ref()
// const getCaseType = async () => {
//   const res = await post('/common/const/getMedicalRecordMode', { mrmType: 0 })
//   caseTypeOptions.value = res.data || []
//   // mrmCode.value = res.data?.[0]?.mrmCode
// }
const timer = ref(null)
// 获取当前医生默认显示的病历
const getMedical = async () => {
  const res = await post('/common/masterData/getByYsbhDepartment', { empId })
  if (res.code !== 0) return message.error(res.msg)
  mrmCode.value = res.data && res.data.blmb
  if (mrmCode.value === 'YKBL2' || mrmCode.value === 'YKBL3') {
    getEyeData()
    getInspectData()
    inspectShow.value = true
    timer.value = setTimeout(() => {
      inspectShow.value = false
    }, 3000)
  }
}
const tranInspect = (val) => {
  inspectShow.value = val
}

//保存病历信息
const onSubmit = async (status, state = true) => {
  const res = await post('outp/mzys/doSavePatientEMR', {
    ...formState.value,
    brId: store.currentPatient.brId,
    jzbh: store.currentPatient.jzbh,
    mrmCode: mrmCode.value,
    qtzdxx: '',
    isCxtj: status ?? undefined,
    isCommit: status ?? undefined
  })
  if (res.code !== 0) return message.error(res.msg)
  //如果是眼科病历二
  if (mrmCode.value === 'YKBL2' || mrmCode.value === 'YKBL3') {
    const form = JSON.parse(JSON.stringify(formData.value))
    EYEChildItems.value.forEach((item) => {
      if (item.key !== '其他检查') return
      if (form[item.valueOS] && form[item.valueOS].length > 0) {
        form[item.valueOS] = form[item.valueOS].join(',')
      }
      if (form[item.valueOD] && form[item.valueOD].length > 0) {
        form[item.valueOD] = form[item.valueOD].join(',')
      }
    })
    const res1 = await post('/OPTOMETY/SaveZKJC', {
      ...form,
      brId: store.currentPatient.brId,
      jzbh: store.currentPatient.jzbh
    })
    if (res1.code !== '0') return message.error(res1.msg)
    if (state) {
      message.success('保存成功')
    } else {
      message.success(status === '1' ? '提交成功' : '撤销成功')
    }
    getEyeData()
  } else {
    if (state) {
      message.success('保存成功')
    } else {
      message.success(status === '1' ? '提交成功' : '撤销成功')
    }
  }
  emit('success')
}
const onTempSuccess = (data) => {
  formState.value = data
}
//获取常规检查
const getInspectData = async () => {
  if (!store.currentPatient.jzbh) return
  const { code, data, msg } = await post('OPTOMETY/getCGJCInfo', { jzbh: store.currentPatient.jzbh, setbh: setbh })
  if (code !== '0') return message.error(msg)
  inspectData.value = data
  if (data.listBLJLB_YG && data.listBLJLB_YG.length > 0) {
    const YGArr = data.listBLJLB_YG.filter((item) => {
      return item.yglb === '电脑验光'
    })
    if (YGArr && YGArr.length > 0) {
      inspectData.value.listBLJLB_YG_DATA = YGArr[0]
    } else {
      inspectData.value.listBLJLB_YG_DATA = {}
    }
  } else {
    inspectData.value.listBLJLB_YG_DATA = {}
  }
}
// 获取眼部检查数据
const getEyeData = async () => {
  if (!store.currentPatient.jzbh) return
  const { code, data, msg } = await post('/OPTOMETY/getZKJCInfo', { jzbh: store.currentPatient.jzbh, setbh: setbh })
  if (code !== '0') return message.error(msg)
  const form = data || {}
  EYEChildItems.value.forEach((item) => {
    if (item.key !== '其他检查') return
    if (form[item.valueOS]) {
      form[item.valueOS] = form[item.valueOS].split(',')
    }
    if (form[item.valueOD] && form[item.valueOD].length > 0) {
      form[item.valueOD] = form[item.valueOD].split(',')
    }
  })
  formData.value = form
}

// 获取病史
const onClickHistory = async () => {
  if (!store.currentPatient.brId) return

  const { code, data, msg } = await post('/outp/mzys/getOutpMedicalHistory', { brId: store.currentPatient.brId })
  if (code !== 0) return message.error(msg)
  message.success(msg)
  data && (formState.value = data)
}

// 打印病历单
const onPrintMedical = async () => {
  const { code, msg, data } = await post('/outp/outPrint/printrptMZBL', { brId: store.currentPatient.brId, jzbh: store.currentPatient?.jzbh })
  if (code !== 0) return message.error(msg)
  window.openExe?.rpt(data) //调用winform打印
}

// 打印病程单
const onPrint = async () => {
  if (mrmCode.value === 'XYBL') {
    printType.value = 0
  } else if (mrmCode.value === 'ZYBL') {
    printType.value = 1
  } else {
    printType.value = 2
  }

  if (isPrintStatus.value === '0' || isPrintStatus.value === '2') {
    const { code, msg, data } = await post('/outp/outPrint/getMZBCD', {
      mzjlbh: store.currentPatient.jzbh,
      pjhm: store.currentPatient.pjhm,
      type: printType.value
    })
    if (code !== 0) return message.error(msg)
    window.openExe?.rpt(data) //调用winform打印
  } else if (isPrintStatus.value === '1') {
    // window.open(`/api/v1/outp/outPrint/printTreatmentSheet?jzbh= ${store.currentPatient.jzbh} `)
    window.open(`${host}/Ajax/CS_Result?page=rptMZXBL_JG&emp_id=${empId}&jzbh=${store.currentPatient.jzbh}&setbh=${setbh}`)
  }
}

// 合并打印
const onPrintS = () => {
  onPrintMedical()
  onPrint()
}

watch(
  () => store.tempCase,
  () => {
    formState.value = store.tempCase
  }
)

const onSelect = (value, code, select, multiple = false) => {
  if (multiple) {
    //多选拼接
    formState.value[value] = formState.value[value] ? formState.value[value] + '，' + select.zdmc || select.mc : select.zdmc || select.mc
    formState.value[code] = formState.value[code] ? formState.value[code] + '，' + select.zddm || select.dm : select.zddm || select.dm
    formState.value['bcLczdIcd10Name'] = formState.value['bcLczdIcd10Name']
      ? formState.value['bcLczdIcd10Name'] + '，' + select.nmiIcd10Name
      : select.nmiIcd10Name
    formState.value['bcLczdIcd10Code'] = formState.value['bcLczdIcd10Code']
      ? formState.value['bcLczdIcd10Code'] + '，' + select.nmiIcd10Code
      : select.nmiIcd10Code
  } else {
    formState.value[value] = select.zdmc || select.mc
    formState.value[code] = select.zddm || select.dm
    formState.value.bcLczdIcd10Code = select.nmiIcd10Code
    formState.value.bcLczdIcd10Name = select.nmiIcd10Name
  }
}

watch(
  () => store.currentPatient.jzbh,
  () => {
    // getCaseType()
    getMedical()
    // getEyeData()
    // getInspectData()
  }
)

watch(
  () => props.activeKey,
  (val) => {
    if (val === '1') {
      formState.value = { ...props.caseData }
      // getCaseType()
      getMedical()
      // getEyeData()
      // getInspectData()
    }
  },
  {
    immediate: true
  }
)

watch(
  () => props.caseData,
  (value) => {
    formState.value = { ...value }
    saveStatus.value = formState.value.bcLczdZddm
    store.currentMedical = formState.value
  },
  { deep: true }
)

// const yqbh = getSystemConfig('OUTP_OPHTH_INSTRUMENT_BH') //仪器编号
// const getPACSUrl = (view, isYqflg = false, isYqbh = false) => {
//   let url = `${host}/Ajax/CS_Result?page=${view}&emp_id=${empId}&jzbh=${store.currentPatient.jzbh}&setbh=${setbh}`
//   isYqflg && (url += `&yqflg=1`)
//   isYqbh && (url += `&yqbh=${yqbh}`)
//   return url
// }
const dynamicConfig = ref({})
const getDynamicUrl = async () => {
  if (!store.currentPatient.jzbh) return
  const { data, code } = await post(`${host}/Ajax/getZLFA_BQB_JZBH?jzbh=${store.currentPatient.jzbh}&setbh=${setbh}`)
  if (code === '0' && data[0]) {
    data[0].url = `${host}/Ajax/CS_Result?page=${data[0].url}&emp_id=${empId}&jzbh=${store.currentPatient.jzbh}&setbh=${setbh}`
    dynamicConfig.value = data[0]
  }
}
const setIframeHeight = (height = 0) => {
  const iframe = document.getElementById('dlgCGJC')
  if (iframe) {
    iframe.height = `${height}px`
  }
}
window.addEventListener('message', (event) => {
  event.data === 'reloadHisTab' && getDynamicUrl()
  event.data.bodyHeight && setIframeHeight(event.data.bodyHeight)
})

onMounted(() => {
  getDynamicUrl()
  isPrintStatus.value = getSystemConfig('OUTP_MEDICAL_DOCUMENT_PRINT_MODE') // 0：通用|1：上海黑马|2：茗视光
  printTitle.value = isPrintStatus.value === '1' ? '打印病历小票' : '打印病程单'
})
onUnmounted(() => {
  clearTimeout(timer.value)
  timer.value = null
})
</script>
<style lang="less" scoped>
.case-table {
  --border-color: rgba(125, 125, 125, 0.16);
  border: 1px solid var(--border-color);
  .case-item {
    display: flex;
    .required {
      position: relative;
      &::before {
        position: absolute;
        top: 8px;
        left: 8px;
        color: red;
        content: '*';
      }
    }
    .label {
      display: flex;
      align-items: center;
      width: 278px;
      height: 54px;
      padding: 8px 16px;
      background-color: #f5f5f5;
      border-right: 1px solid var(--border-color);
      border-bottom: 1px solid var(--border-color);
    }
    .label-eye {
      display: flex;
      align-items: center;
      width: 278px;
      background-color: #f5f5f5;
      border-right: 1px solid var(--border-color);
      border-bottom: 1px solid var(--border-color);
      .eye-border-left {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 94px;
        .eye-border-left-con {
          padding: 8px 16px;
        }
      }
      .eye-border-right {
        width: 184px;
        border-left: 1px solid var(--border-color);
        .eye-border-right-con {
          padding: 8px 10px 8px 16px;
          border-bottom: 1px solid var(--border-color);
        }
        .eye-border-right-con:last-child {
          border-bottom: none;
        }
      }
    }
    .content {
      flex: 1;
      overflow: hidden;
      border-bottom: 1px solid var(--border-color);
      :deep(.ant-input) {
        height: 100%;
        border: none;
        border: 1px solid transparent;
        border-radius: 0;
        &:focus {
          background: var(--edit-cell-color);
          border: 1px solid var(--primary-color);
          box-shadow: none;
        }
        &:hover {
          background: var(--bg-color);
          border: 1px solid var(--primary-color);
        }
      }
      :deep(.ant-select) {
        height: 100%;
        padding-top: 3px;
        border: 1px solid transparent;
        border-radius: 0;
        &:focus {
          background: var(--edit-cell-color);
          border: 1px solid var(--primary-color);
          box-shadow: none;
        }
        &:hover {
          background: var(--bg-color);
          border: 1px solid var(--primary-color);
        }
      }
      :deep(.ant-input-affix-wrapper) {
        height: 100%;
        background: var(--bg-color);
        border: 1px solid transparent;
        border-radius: 0;
        &-focused {
          border: 1px solid var(--primary-color);
          box-shadow: none;
        }
        &:hover {
          background: var(--bg-color);
          border: 1px solid var(--primary-color);
        }
        .ant-input {
          border: none;
        }
      }
      .eye-box {
        background-color: #f5f5f5;
        .eye-box-header-left {
          display: flex;
          align-items: center;
          justify-content: center;
          width: 50%;
          border-right: 1px solid var(--border-color);
          border-bottom: 1px solid var(--border-color);
        }
        .eye-box-header-right {
          display: flex;
          align-items: center;
          justify-content: center;
          width: 50%;
          border-bottom: 1px solid var(--border-color);
        }
      }
      .eye-item-box {
        border-bottom: 1px solid var(--border-color);
        .eye-box-left {
          display: flex;
          align-items: center;
          justify-content: center;
          width: 50%;
          height: 100%;
          border-right: 1px solid var(--border-color);
          .eye-box-left-br {
            border-right: 1px solid var(--border-color);
          }
        }
        .eye-box-right {
          display: flex;
          align-items: center;
          justify-content: center;
          width: 50%;
          height: 100%;
          .eye-box-right-br {
            border-right: 1px solid var(--border-color);
          }
        }
      }
      .eye-wrap:last-child {
        .eye-item-box {
          border-bottom: none;
        }
      }
    }
    &:last-child {
      .content,
      .label {
        align-items: flex-start;
        border-bottom: none;
      }
    }
  }
}
.no-data {
  display: flex;
  align-items: center;
  height: 100%;
  padding-left: 12px;
}
</style>
